using Autofac;
using Autofac.Extensions.DependencyInjection;
using Loong.Modules;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Loong.Web.Api
{
    public class Startup
    {
        private readonly ModuleManager _moduleManager;

        public Startup(IConfiguration configuration)
        {
            _moduleManager = new ModuleManager();

            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            _moduleManager.ConfigureServices(services, Configuration);
        }

        public void ConfigureContainer(ContainerBuilder builder)
        {
            _moduleManager.ConfigureContainer(builder);
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddLog4Net();

            _moduleManager.Initialize(app.ApplicationServices.GetAutofacRoot());

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            lifetime.ApplicationStopping.Register(() =>
            {
                _moduleManager.Shutdown();
            });
        }
    }
}
